package org.example;

import java.util.ArrayList;
import java.util.List;

public class Test2 {
    //leetcode LCR 146 螺旋遍历二维数组 https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/
    //
    public int[] spiralArray(int[][] array) {
        int x = 0, y = 0, count = 0;
        int n1 = array.length;
        if (n1 == 0) return new int[0];
        int n2 = array[0].length;
        int xl = 0, xr = n2 - 1, yt = 0, yb = n1 - 1;
        int[] ret = new int[n1 * n2];
        int index = 0;
        while (index < ret.length) {
            while (index < ret.length && y <= xr) {
                ret[index++] = array[x][y++];
                count++;
            }
            x++;
            y--;
            xr--;
            while (index < ret.length && x < yb) {
                ret[index++] = array[x++][y];
                count++;
            }
            yb--;
            while (index < ret.length && y > xl) {
                ret[index++] = array[x][y--];
                count++;
            }
            xl++;
            while (index < ret.length && x > yt) {
                ret[index++] = array[x--][y];
                count++;
            }
            yt++;
            x++;
            y++;
        }
        return ret;
    }

    //leetcode 54 螺旋矩阵 https://leetcode.cn/problems/spiral-matrix/description/
    public List<Integer> spiralOrder(int[][] matrix) {
        int x = 0, y = 0, count = 0;
        int n1 = matrix.length;
        if (n1 == 0) return new ArrayList<>();
        int n2 = matrix[0].length;
        int xl = 0, xr = n2 - 1, yt = 0, yb = n1 - 1;
        List<Integer> ret = new ArrayList<>(n1 * n2);
        int index = 0;
        while (ret.size() < n1 * n2) {
            while (ret.size() < n1 * n2 && y <= xr) {
                ret.add(matrix[x][y++]);
            }
            x++;
            y--;
            xr--;
            while (ret.size() < n1 * n2 && x < yb) {
                ret.add(matrix[x++][y]);
            }
            yb--;
            while (ret.size() < n1 * n2 && y > xl) {
                ret.add(matrix[x][y--]);
            }
            xl++;
            while (ret.size() < n1 * n2 && x > yt) {
                ret.add(matrix[x--][y]);
            }
            yt++;
            x++;
            y++;
        }
        return ret;
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        test2.spiralOrder(arr);
        System.out.println(666);
    }
}
